<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Web 端一键登录示例</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 800px;
      margin: 50px auto;
      padding: 20px;
      background: #f5f5f5;
    }
    .container {
      background: white;
      padding: 30px;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    h1 {
      color: #333;
      margin-bottom: 30px;
    }
    .form-group {
      margin-bottom: 20px;
    }
    label {
      display: block;
      margin-bottom: 5px;
      color: #666;
      font-weight: bold;
    }
    input, textarea {
      width: 100%;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
      box-sizing: border-box;
    }
    textarea {
      min-height: 100px;
      resize: vertical;
      font-family: monospace;
    }
    button {
      background: #409eff;
      color: white;
      border: none;
      padding: 12px 24px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 16px;
      margin-right: 10px;
    }
    button:hover {
      background: #66b1ff;
    }
    button:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
    .result {
      margin-top: 20px;
      padding: 15px;
      border-radius: 4px;
      display: none;
    }
    .result.success {
      background: #f0f9ff;
      border: 1px solid #409eff;
      color: #409eff;
      display: block;
    }
    .result.error {
      background: #fef0f0;
      border: 1px solid #f56c6c;
      color: #f56c6c;
      display: block;
    }
    .tips {
      background: #fff7e6;
      border: 1px solid #ffd591;
      padding: 15px;
      border-radius: 4px;
      margin-bottom: 20px;
      color: #ad6800;
    }
    .tips strong {
      display: block;
      margin-bottom: 8px;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>Web 端一键登录示例</h1>

    <div class="tips">
      <strong>💡 使用说明：</strong>
      <ul style="margin: 8px 0; padding-left: 20px;">
        <li>确保 Electron 桌面程序已启动</li>
        <li>每个不同的 shopId 会创建一个新窗口（多开）</li>
        <li>相同 shopId 会聚焦到已有窗口</li>
        <li>每个窗口使用独立的 Cookie（完全隔离）</li>
      </ul>
    </div>

    <div class="form-group">
      <label for="url">网页地址 (URL):</label>
      <input type="text" id="url" value="https://e.waimai.meituan.com" placeholder="https://example.com">
    </div>

    <div class="form-group">
      <label for="cookies">Cookie 字符串:</label>
      <textarea id="cookies" placeholder="token=xxx; wmPoiId=123; acctId=456">token=test123; wmPoiId=88888; acctId=99999</textarea>
    </div>

    <div class="form-group">
      <label for="shopId">店铺 ID (用于多开隔离):</label>
      <input type="text" id="shopId" value="shop_001" placeholder="shop_001">
      <small style="color: #999; display: block; margin-top: 5px;">
        不同的 shopId 会创建不同的窗口，相同的 shopId 会聚焦到已有窗口
      </small>
    </div>

    <div class="form-group">
      <label for="shopName">店铺名称 (可选):</label>
      <input type="text" id="shopName" value="测试店铺" placeholder="我的店铺">
    </div>

    <button id="loginBtn" onclick="handleLogin()">一键登录</button>
    <button onclick="handleLoginMultiple()">多开测试（打开3个窗口）</button>
    <button onclick="checkStatus()">检查连接状态</button>

    <div id="result" class="result"></div>
  </div>

  <script>
    const ELECTRON_COMM_URL = 'http://127.0.0.1:8888'

    // 显示结果
    function showResult(message, isError = false) {
      const resultDiv = document.getElementById('result')
      resultDiv.className = `result ${isError ? 'error' : 'success'}`
      resultDiv.textContent = message

      if (!isError) {
        setTimeout(() => {
          resultDiv.style.display = 'none'
        }, 3000)
      }
    }

    // 检查 Electron 是否运行
    async function checkStatus() {
      try {
        const response = await fetch(ELECTRON_COMM_URL, {
          method: 'OPTIONS',
          mode: 'no-cors'
        })
        showResult('✓ Electron 桌面程序已连接')
      } catch {
        showResult('✗ Electron 桌面程序未运行，请先启动桌面程序', true)
      }
    }

    // 发送登录指令
    async function sendLoginCommand(data) {
      try {
        const response = await fetch(ELECTRON_COMM_URL, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data)
        })

        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`)
        }

        const result = await response.json()
        return result
      } catch (error) {
        throw new Error(`无法连接到 Electron 桌面程序: ${error.message}`)
      }
    }

    // 处理登录
    async function handleLogin() {
      const btn = document.getElementById('loginBtn')
      btn.disabled = true

      try {
        const url = document.getElementById('url').value
        const cookies = document.getElementById('cookies').value
        const shopId = document.getElementById('shopId').value
        const shopName = document.getElementById('shopName').value

        if (!url || !shopId) {
          showResult('请填写必填项：URL 和 店铺ID', true)
          return
        }

        const result = await sendLoginCommand({
          url,
          cookies: cookies || undefined,
          shopId,
          shopName: shopName || undefined
        })

        if (result.success) {
          showResult(`✓ ${result.message} (操作: ${result.action || 'open'})`)
        } else {
          showResult(`✗ ${result.message}`, true)
        }
      } catch (error) {
        showResult(`✗ ${error.message}`, true)
      } finally {
        btn.disabled = false
      }
    }

    // 多开测试
    async function handleLoginMultiple() {
      const btn = document.getElementById('loginBtn')
      btn.disabled = true

      try {
        const baseUrl = document.getElementById('url').value
        const baseCookies = document.getElementById('cookies').value
        const baseShopName = document.getElementById('shopName').value

        // 同时打开3个不同的窗口
        const promises = [1, 2, 3].map(async (index) => {
          return sendLoginCommand({
            url: baseUrl,
            cookies: baseCookies || undefined,
            shopId: `shop_${index}`,
            shopName: `${baseShopName || '店铺'}_${index}`
          })
        })

        const results = await Promise.all(promises)
        const successCount = results.filter(r => r.success).length

        showResult(`✓ 成功打开 ${successCount}/3 个窗口`)
      } catch (error) {
        showResult(`✗ ${error.message}`, true)
      } finally {
        btn.disabled = false
      }
    }

    // 页面加载时检查状态
    window.onload = () => {
      checkStatus()
    }
  </script>
</body>
</html>
